package com.yby6.web.controller.other;

// Create By Yang Shuai,Date 2022/4/21:17:51

import cn.hutool.core.net.URLEncodeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yby6.common.exception.CustomException;
import com.yby6.common.utils.http.HttpsUtils;
import com.yby6.system.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yby6.common.core.AjaxResult;
import com.yby6.common.core.domain.SysUser;
import com.yby6.common.utils.BCryptUtil;
import com.yby6.common.utils.ServletUtils;
import com.yby6.common.utils.StringUtils;
import com.yby6.framework.web.service.SysLoginService;
import com.yby6.system.vo.Gitee.GiteeVo;
import com.yby6.system.vo.SysUserVo;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/system/gitee")
@RequiredArgsConstructor
public class GiteeController {
    private final SysUserService sysUserService;

    private final SysLoginService sysLoginService;


    @GetMapping("/{code}")
    public AjaxResult getGiteeInfo(@PathVariable String code) {
        Map<String, String> params = new LinkedHashMap<>(5);
        try {
            String url = "https://gitee.com/oauth/token";
            //申请应用时分配的AppKey
            params.put("client_id", "5d07816cb64f92a083c984baafb6e20aa4a95520a9758633a6f780952dd98b7d");
            //申请应用时分配的AppSecret
            params.put("client_secret", "16a2b06fae9f33931f7d8e5c14b6d95d36bba534b3a486f807313d3abe32a2a1");
            //请求的类型，填写authorization_code
            params.put("grant_type", "authorization_code");
            //调用authorize获得的code值
            params.put("code", code);
            //回调地址，需需与注册应用里的回调地址一致。
            params.put("redirect_uri", URLEncodeUtil.encode("https://lzys522.cn/#/login"));
            // 发送请求获取token
            String result = HttpsUtils.post(url, params);
            JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
            url = "https://gitee.com/api/v5/user";
            // 根据token请求
            String getUserInfo = HttpsUtils.get(url, jsonObject.get("access_token"));
            if (StringUtils.isNull(getUserInfo)) {
                throw new CustomException("Gitee拉取用户信息失败！");
            }
            // 转换实体
            GiteeVo giteeVo = JSON.parseObject(getUserInfo, GiteeVo.class);
            log.info("gitee返回的用户信息：{}", giteeVo);
            log.info("gitee返回的用户JSON：{}", getUserInfo);
            // 开始鉴权登陆

            SysUserVo sysUserVo = BuildUserClass(giteeVo);
            // 1.判断是否存在该用户
            SysUser userByOpenId = this.sysUserService.getUserByOpenId(sysUserVo.getOpenId());
            if (userByOpenId != null && userByOpenId.getId() != null) {
                this.sysUserService.updateByOpenId(sysUserVo);
            } else {
                this.sysUserService.insert(sysUserVo);
            }
            SysUser sysUser = this.sysUserService.getUserByOpenId(sysUserVo.getOpenId());
            Serializable id = sysLoginService.login(sysUser, ServletUtils.getRequest());
            return AjaxResult.success().addParam("token", String.valueOf(id));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("第三方登录错误：{}", e.getCause().getLocalizedMessage());
        }
        return AjaxResult.error();
    }

    /**
     * GiteeVo转实体SysUserVo
     *
     * @param giteeVo
     * @return SysUserVo
     */
    private SysUserVo BuildUserClass(GiteeVo giteeVo) {
        Long[] roleIds = new Long[]{11L};
        return new SysUserVo().builder().openId(giteeVo.getId())
                .nickName(giteeVo.getLogin() + "-" + giteeVo.getName())
                .username(giteeVo.getLogin() + giteeVo.getId())
                .header(giteeVo.getAvatar_url()).type(3)
                .password(BCryptUtil.createPassword("123456") + giteeVo.getId())
                .note("Gitee登录-" + giteeVo.getName()).roleIds(roleIds).status(1).build();
    }
}